﻿using System;
using System.Windows;
using System.Windows.Data;
using System.Globalization;

using SBPweb.RIA.Client.Contracts.Base;

namespace SBPweb.RIA.Client.Controls.Converters
{

    public class ExtendableBagConverter : DependencyObjectBase, IValueConverter
    {

        #region Dependency definitions

        public static readonly DependencyProperty BagProperty = DependencyProperty.Register("Bag", typeof(ExtendableBag), typeof(ExtendableBagConverter), null);

        #endregion

        #region Constructor logic

        public ExtendableBagConverter()
        {
        }

        public ExtendableBagConverter(ExtendableBag bag)
        {
            Bag = bag;
        }

        #endregion

        #region Properties

        public ExtendableBag Bag
        {
            get
            {
                return base.GetTypedValue<ExtendableBag>(BagProperty);
            }
            set
            {
                SetTypedValue<ExtendableBag>(BagProperty, value, "Bag");
            }
        }

        #endregion

        #region Methods

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (parameter != null)
            {
                string param = parameter.ToString();

                if (Bag != null && Bag.Contains(param))
                {
                    return Bag[param];
                }
            }

            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (parameter != null)
            {
                string param = parameter.ToString();

                if (Bag != null)
                {
                    return Bag[param] = value;
                }
            }

            return null;
        }

        public Binding GetBinding(object source, string bagKey)
        {
            return GetBinding(source, bagKey, null);
        }

        public Binding GetBinding(object source, string bagKey, object targetNullValue)
        {
            Binding binding = new Binding();
            binding.Converter = this;
            binding.ConverterParameter = bagKey;
            binding.Mode = BindingMode.TwoWay;
            binding.Source = source;
            binding.Path = new PropertyPath("DataContext");
#if !WINDOWS_PHONE
            if (targetNullValue != null)
            {
                binding.TargetNullValue = targetNullValue;
            }
#endif
            return binding;
        }

        #endregion

    }

}
